<template>
  <el-card>
    <el-form ref="form" :model="form" label-width="80px" inline>
      <el-form-item label="一级分类">
        <el-select
          v-model="category1Id"
          :disabled="disabled"
          placeholder="请选择一级分类列表"
        >
          <el-option
            v-for="c1 in getCategory1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          :disabled="disabled"
          v-model="category2Id"
          placeholder="请选择二级分类列表"
        >
          <el-option
            :label="c2.name"
            v-for="c2 in getCategory2List"
            :key="c2.id"
            :value="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          @change="c3Change"
          :disabled="disabled"
          v-model="form.category3Id"
          placeholder="请选择三级分类列表"
        >
          <el-option
            :label="c3.name"
            v-for="c3 in getCategory3List"
            :key="c3.id"
            :value="c3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from "@/api/product/attr/attr";
export default {
  name: "CategorySelector",
  props: {
    disabled: Boolean,
  },
  data() {
    return {
      form: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      getCategory1List: [],
      getCategory2List: [],
      getCategory3List: [],
    };
  },
  async mounted() {
    const res = await getCategory1ListApi();
    this.getCategory1List = res.data;
  },
  computed: {
    category1Id: {
      get() {
        return this.form.category1Id;
      },
      async set(category1Id) {
        this.form.category1Id = category1Id;
        const res = await getCategory2ListApi(category1Id);
        this.getCategory2List = res.data;
        (this.form.category2Id = ""),
          (this.form.category3Id = ""),
          (this.getCategory3List = []);
        this.$emit("changeCategory", { id: this.form.category1Id, level: 1 });
      },
    },
    category2Id: {
      get() {
        return this.form.category2Id;
      },
      async set(category2Id) {
        this.form.category2Id = category2Id;
        const res = await getCategory3ListApi(category2Id);
        this.getCategory3List = res.data;
        this.form.category3Id = "";
        this.$emit("changeCategory", { id: this.form.category2Id, level: 2 });
      },
    },
  },
  methods: {
    c3Change() {
      this.$emit("changeCategory", { id: this.form.category3Id, level: 3 });
    },
  },
};
</script>

<style></style>
